@tableland/sdk
![standard-readme compliant](https://img.shields.io/badge/standard--readme-OK-green.svg)
Tableland JavaScript SDK—the essential tool for building web3 apps with Tableland databases.
Table of Contents
Background
The @tableland/sdk
library provides an easy-to-use interface for integrating Tableland databases into your web3 applications, unlocking decentralized data-driven development with SQL queries (creates, writes, reads) and access control.
Install
You can install via npm:
npm i @tableland/sdk
Or yarn:
yarn add @tableland/sdk
Usage
Full library documentation is available on our docs site.
Database
A Database
is used to create, write, and read data. To connect to a Database
, you first must import and instantiate it. There are two key considerations:
- If you are only reading data, you do not need a signer, which is an abstraction of an EVM account and used for sending on-chain transactions—database reads are off-chain.
- If you are creating or writing to tables, you do need a signer since database mutations require an EVM account to send transactions.
If you need to set up a signer, libraries like ethers
help provide a way to create one by leveraging a connection with a provider
. From there, all database creates, writes, and reads go through a single prepare
method.
Connecting
As noted, creating a table instantiates a Database
and must connect to it with a signer; this is also true for any table writes. The ethers
library is used in the example below to create a signer, which comes as part of the @tableland/sdk
but can also be installed separately.
import { Database } from "@tableland/sdk";
import { providers } from "ethers";
const provider = new providers.Web3Provider(window.ethereum);
await provider.send("eth_requestAccounts", []);
const signer = provider.getSigner();
const db = new Database({ signer });
For certain applications, it's possible that developers will want to manage connections from a local wallet and not a browser wallet. You'll want to create a provider connection using a custom provider URL or the default ethers provider for the specified chain.
import { Database } from "@tableland/sdk";
import { Wallet, getDefaultProvider } from "ethers";
const privateKey = PRIVATE_KEY;
const wallet = new Wallet(privateKey);
const provider = getDefaultProvider("homestead");
const signer = wallet.connect(provider);
const db = new Database({ signer });
For read-only connections, a signer is not required. This Database
connection can be used to make multichain queries across any of the chains in which Tableland is deployed to. Note that in the signer-connected Database
above, read queries are still possible.
import { Database } from "@tableland/sdk";
const db = new Database();
If no signer
is provided and you try to create or write to tables, the Database
will default to prompting a browser wallet connection.
Create, write, & read
To create a table, you pass a CREATE TABLE
statement to the prepare
method and then execute it.
const prefix = "my_sdk_table";
const { meta: create } = await db
.prepare(`CREATE TABLE ${prefix} (id integer primary key, val text);`)
.run();
const { name } = create.txn;
Once the table is created, you can then insert, update, and/or delete data with prepared statements. Parameter binding is a useful feature such that you can pass parameters in bind
that replace the ?
placeholders in this example.
const { meta: insert } = await db
.prepare(`INSERT INTO ${name} (id, val) VALUES (?, ?);`)
.bind(0, "Bobby Tables")
.run();
await insert.txn.wait();
Notice the insert.txn.wait()
usage above. Table creates and writes are on-chain actions, so a transaction must be "finalized" before the data is made available via a SELECT
query. Once the data is settled, it can be read.
const { results } = await db.prepare(`SELECT * FROM ${name};`).all();
Validator
Aside from the core Database
, developers can also choose to connect directly to a Tableland Validator
node. Connecting to a validator is useful when you'd like to directly access other table or validator information as exposed by a Tableland Gateway API.
A validator is instantiated using a Database
. The Database
does not need a signer, but it does need a baseUrl
to be defined, which helps to explicitly define which chain is being used. The exported helpers
has a useful getBaseUrl
method that forms the baseUrl
based on a passed chain ID number.
For example, assuming you've already established a provider, you can connect to a Validator
and retrieve node health info.
import { Database, Validator, helpers } from "@tableland/sdk";
const { chainId } = await provider.getNetwork();
const db = new Database({
baseUrl: helpers.getBaseUrl(chainId),
});
const validator = new Validator(db.config);
console.log(validator);
const isHealthy = await validator.health();
console.log(isHealthy);
Registry
The SDK is in-part a JavaScript abstraction of the core Tableland registry smart contract. Developers can choose to interact directly with the Registry
API for table creates and writes, if desired. It also offers a couple of additional features, such as listing all tables owned by an address or transferring table ownership altogether.
Since these are on-chain interactions, a signer is needed to interact with the Registry
on a specific chain.
import { Database, Registry, helpers } from "@tableland/sdk";
const db = new Database({ signer });
const registry = await new Registry(db.config);
const tables = await registry.listTables();
console.log(tables);
const to = "0x1234...";
const tx = await reg.safeTransferFrom({
to,
tableName: "{name}_{prefix}_{chainId}",
});
await tx.wait();
Build Tools
The Tableland SDK uses an optimized WASM build of our SQL parser under the hood. Unfortunately, some build systems such as Vite require an adjustment to their configuration to support this feature. To temporarily work around this issue, simply add @tableland/sqlparser
to the excluded
list under optimizeDeps
in your vite.config.ts
file:
optimizeDeps: {
exclude: ["@tableland/sqlparser"];
}
See our own Rigs project for an example of using this in production.
Development
Get started by cloning, installing, building, and testing the project:
git clone git@github.com:tablelandnetwork/js-tableland.git
cd js-tableland
npm install
npm run build
npm test
To run tests in a few of the common browser environments we are using Playwright. Once your code changes are finished you can run the brower tests by doing:
cd test/browser/server
npm install
cd ../../
npm run test:browser
Contributing
PRs accepted.
Small note: If editing the README, please conform to the
standard-readme specification.
License
MIT AND Apache-2.0, © 2021-2023 Tableland Network Contributors